﻿var mapid = "";
var deviceid ="";
var isPostBack=true;


$(function(){//设置起止日期显示在input上方
    //开始时间-结束时间
    $(".form_date_start").datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        pickerPosition: 'top-right',
        autoclose: true,
        minView: "month",
        maxView: "decade",
        todayBtn: true,
        clearBtn: true
    }).on("click", function (ev) {
        $(".form_date_start").datetimepicker("setEndDate", $(".form_date_end").val());
    });

    $(".form_date_end").datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        pickerPosition: 'top-right',
        autoclose: true,
        minView: "month",
        maxView: "decade",
        todayBtn: true,
        clearBtn: true
    }).on("click", function (ev) {
        $(".form_date_end").datetimepicker("setStartDate", $(".form_date_start").val());
    });
})
//切换选项
var myTab = 1;//默认优先显示运行日志
$("#myTabs li").on("click",function(){
    isPostBack = true;//重新加载分页
    $("#startTime,#endTime").val("");//清空起止时间
    if($(this).index()==1) {
        myTab = 2;
        getDeviceReport(deviceid,1);
    } else {
        myTab = 1;
        getDeviceDetail(deviceid,1);
    }
});

//获取所有子设备
function getDevice(floorId){
    mapid = floorId;
    $("#" + mapid).html("");
    // PostForm("/cwp/front/sh/device!execute", "uid=d001_2&pageSize=100&currentPage=1&deviceTypeId=1004&buildingId="+floorId, "", outputDevice, '');
    // PostForm("/cwp/front/sh/device!execute", "uid=d001&pageSize=100&currentPage=1&deviceTypeId=1003190&buildingId="+floorId, "", outputDeviceZ, '');

    $.getJSON('/cwp/src/json/device/door/device_door_d001_2.json',function(data){
        outputDevice(data);
    })

    $.getJSON('/cwp/src/json/device/door/device_door_d001.json',function(data){
        outputDeviceZ(data);
    })
}

function outputDevice(result){
    if(result.returnCode  == 0){
        var astr = "";
        for(var i=0;i<result.beans.length;i++){
            if(result.beans[i].deviceState=="0"){
                astr += "<a class='menjin' data-id="+result.beans[i].deviceId +" data-ip="+result.beans[i].controllerip +"  data-interfaceaddr="+result.beans[i].interfaceaddr +"   title="+result.beans[i].devicePositionDescribe+" style='left:"+result.beans[i].deviceX+"%;top:"+ result.beans[i].deviceY +"%'><img src='/cwp/src/assets/img/menjin1-1.png'/> </a>";
            }
            else {
                astr += "<a class='menjin' data-id="+result.beans[i].deviceId +" data-ip="+result.beans[i].controllerip +"  data-interfaceaddr="+result.beans[i].interfaceaddr +"   title="+result.beans[i].devicePositionDescribe+" style='left:"+result.beans[i].deviceX+"%;top:"+ result.beans[i].deviceY +"%'><img src='/cwp/src/assets/img/menjin2-1.png'/> </a>";
            }
        }
        $("#" + mapid).html($("#" + mapid).html() + astr);
    }else{
        tipModal("icon-cross", "获取设备失败");
    }
}
function outputDeviceZ(result){
    if(result.returnCode  == 0){
        var astr = "";
        for(var i=0;i<result.beans.length;i++){
            if(result.beans[i].deviceState=="0"){
                astr += "<a class='menjin' data-id="+result.beans[i].deviceId +" data-ip="+result.beans[i].controllerip +"  data-interfaceaddr="+result.beans[i].interfaceaddr +"   title="+result.beans[i].devicePositionDescribe+" style='left:"+result.beans[i].deviceX+"%;top:"+ result.beans[i].deviceY +"%'><img src='/cwp/src/assets/img/menjinZ1-1.png'/> </a>";
            }
            else {
                astr += "<a class='menjin' data-id="+result.beans[i].deviceId +" data-ip="+result.beans[i].controllerip +"  data-interfaceaddr="+result.beans[i].interfaceaddr +"   title="+result.beans[i].devicePositionDescribe+" style='left:"+result.beans[i].deviceX+"%;top:"+ result.beans[i].deviceY +"%'><img src='/cwp/src/assets/img/menjinZ2-1.png'/> </a>";
            }
        }
        $("#" + mapid).html($("#" + mapid).html() + astr);
    }else{
        tipModal("icon-cross", "获取设备失败");
    }
}
//点击设备点查看设备详情
//给坐标点绑定点击事件 根据设备ID查看设备详情
$(document).on("click",".menjin",function(){
    //isFirst=true;

    $("#faultAlarmTabTotal").html("共0条数据");
    $(".menjin").removeClass("cur");
    $(this).addClass("cur")
    displayLog($(this).attr("data-id"));
    var deviceId = $(this).attr("data-id");
    $("#btnCloseList").attr("data-id",deviceId);

    //绑定门禁IP及门禁
    isPostBack = true;
    getDeviceDetail(deviceId,1);
    getdeviceInfo(deviceId);
    getDeviceReport(deviceId,1);
});
//门禁日志

function getDeviceDetail(deviceId,pageIndex){
    $("#deviceReportTotal").html("共0条数据");
    deviceid = deviceId;
    //var loaderDeviceDetailTab = new LoaderTableNew("faultAlarmTab","/cwp/front/sh/device!execute","uid=access001&deviceId="+deviceId,1,10,outputDeviceDetail,"",paginationDeviceDetail);
    $.getJSON('/cwp/src/json/device/door/device_info_access001.json',function(data){
            var loaderDeviceDetailTab = new LoaderTable("workLog","faultAlarmTab","/cwp/front/sh/device!execute","uid=access001&deviceId="+deviceId,pageIndex,10,workingLog,"","frmSearch");
                
            workingLog(data);    
            loaderDeviceDetailTab.loadSuccessed(data);    

            // loaderDeviceDetailTab.Display();
    })

}
function workingLog(result){
    var thead="<thead>"+
        "<tr>"+
        "<th>ID</th>"+
        "<th>姓名</th>"+
        "<th>卡号</th>"+
        "<th>时间</th>"+
        "<th>事件</th>"+
        "</tr>"+
        "</thead>";
    var tbodys= "<tbody>";
    for(var i=0;i<result.beans.length;i++) {
        tbodys += "<tr>" +
            "<td>" +  result.beans[i].cardId + "</td>" +
            "<td>" +  result.beans[i].staffName + "</td>" +
            "<td>" +  result.beans[i].staffNo + "</td>" +
            "<td>" +  result.beans[i].createtime + "</td>" +
            "<td>" +  result.beans[i].eventName + "</td>" +
            "</tr>"
    }
    tbodys+= "</tbody>";
    $("#faultAlarmTab").html(thead+tbodys);
    if(result.object.totalPage > 1){
        $("#faultAlarmTabPagination").show();
    }else{
        $("#faultAlarmTabPagination").hide();
    }
}
//门禁告警
function getDeviceReport(deviceId,pageIndex){
    $("#deviceReportTotal").html("共0条数据");
    deviceid = deviceId;
    //var loaderDeviceReportTab = new LoaderTableNew("deviceReport","/cwp/front/sh/warningEvent!execute","uid=waringEvent001&deviceId="+deviceId,1,10,outputDeviceReport,"",paginationgetDeviceReport);
        
    $.getJSON('/cwp/src/json/device/door/device_info_warning_we001.json',function(data){
        var loaderDeviceReportTab = new LoaderTable("guardAlarm","deviceReport","/cwp/front/sh/warningEvent!execute","uid=waringEvent001&deviceId="+deviceId,pageIndex,10,gatingAlarm,"","frmSearch");
        
        gatingAlarm(data);
        loaderDeviceReportTab.loadSuccessed(data);    
        // loaderDeviceReportTab.Display();
    })
}
function gatingAlarm(result){
    var thead="<thead>"+
        "<tr>"+
        "<th>告警编号</th>"+
        "<th>来源</th>"+
        "<th>描述</th>"+
        "<th>时间</th>"+
        "<th>状态</th>"+
        "</tr>"+
        "</thead>";
    var tbodys= "<tbody>";
    for(var i=0;i<result.beans.length;i++) {
        if(result.beans[i].eventFromSystem == 1){
            result.beans[i].eventFromSystemStr = "系统";
        }else{
            result.beans[i].eventFromSystemStr = "手动";
        }
        if(result.beans[i].eventProcessStatus == 1){
            result.beans[i].eventProcessStatusStr = "未处理";
        }else if(result.beans[i].eventProcessStatus == 2){
            result.beans[i].eventProcessStatusStr = "处理中";
        }else if(result.beans[i].eventProcessStatus == 3){
            result.beans[i].eventProcessStatusStr = "已处理";
        }else{
            result.beans[i].eventProcessStatusStr = "未知";
        }
        tbodys += "<tr>" +
            "<td>" +  result.beans[i].alarmNumber + "</td>" +
            "<td>" +  result.beans[i].eventFromSystemStr + "</td>" +
            "<td>" +  result.beans[i].eventDescribe + "</td>" +
            "<td>" +  result.beans[i].applyTime + "</td>" +
            "<td>" +  result.beans[i].eventProcessStatusStr + "</td>" +
            "</tr>"
    }
    tbodys+= "</tbody>";
    $("#deviceReport").html(thead+tbodys);
    if(result.object.totalPage > 1){
        $("#deviceReportPagination").show();
    }else{
        $("#deviceReportPagination").hide();
    }
}
function paginationCallback(page_index){
    if(!isPostBack) {
        switch(myTab){
            case 1:
                getDeviceDetail(deviceid,page_index+1);
                break;
            case 2:
                getDeviceReport(deviceid,page_index+1);
                break;
            default:
                break;
        }
    }
}
//起止日期查询
$("#btnSearchFault").on("click",function(){
    isPostBack = true;//重新加载分页
    var startTime = $("#startTime").val();
    var endTime = $("#endTime").val();
    if(!startTime || !endTime){
        tipModal("icon-cross", "请选择起止日期");
        return false;
    }
    switch(myTab){
        case 1:
            getDeviceDetail(deviceid,1);
            break;
        case 2:
            getDeviceReport(deviceid,1);
            break;
        default:
            break;
    }
});
// function paginationDeviceDetail(page_index){
//     if(!isPostBack) {
//         getDeviceDetail();
//     }
// }
// function paginationgetDeviceReport(page_index){
//     if(!isPostBack) {
//         getDeviceReport();
//     }
//}
// function outputDeviceDetail(result){
//     if(result.returnCode == 0){
//         var outHtml = template("deviceDetailTmpl", result);
//         $("#faultAlarmTab tbody").html(outHtml);
//         //if(result.beans.length >3){
//             //$("#faultAlarmTabTotal").html("共3条数据");
//         //}else{
//             $("#faultAlarmTabTotal").html("共"+ result.beans.length +"条数据");
//         //}

//     }else{
//         tipModal("icon-cross", "获取数据失败");
//     }

// }
// function outputDeviceReport(result){
//     if(result.returnCode == 0){
//         template.helper('eventFromSystemFormat', function (inp) {
//             if (inp == "1") {
//                 return '系统';
//             } else  {
//                 return '手动';
//             }
//         });
//         template.helper('eventProcessStatusFormat', function (inp) {
//             if (inp == "1") {
//                 return "未处理";
//             } else if (inp == "2") {
//                 return "处理中";
//             } else if (inp == "3") {
//                 return "已处理";
//             }
//         });
//         var outHtml = template("deviceReportTmpl", result);
//         $("#deviceReport tbody").html(outHtml);
//         if(result.beans.length >3){
//             $("#deviceReportTotal").html("共3条数据");
//         }else{
//             $("#deviceReportTotal").html("共"+ result.beans.length +"条数据");
//         }

//     }else{
//         tipModal("icon-cross", "获取数据失败");
//     }

// }
//获取设备信息
function getdeviceInfo(deviceId){
    PostForm("/cwp/front/sh/intebuilding!execute", "uid=i003&deviceId="+deviceId, "", outputDeviceInfo, '',"");
}

function outputDeviceInfo(result){
    if(result.returnCode == 0){
        var outHtml = template("deviceInfoTmpl", result);
        $("#deviceInfo").html(outHtml);
    }else{
        tipModal("icon-cross", "获取数据失败");
    }

}

//显示日志
function displayLog(newDeviceId){
    var deviceId = $("#hidDeviceID").val();
    if(deviceId != ""){

    }
    else if(deviceId == newDeviceId){

    }
    else{
        $(".info-box").show();
        $(".info-box").addClass("show");
        var theight=$(".t-building")[0].offsetHeight;
        var infoBoxHeight=$(".info-box")[0].offsetHeight;
        $(".t-building").css("height",theight-infoBoxHeight-20+"px");
        setTimeout(function() {
            autoWidth();
        }, 250);
    }
    $("#hidDeviceID").val(newDeviceId);
}


//关闭日志
$("#btnCloseList").on("click",function(){
    $("#hidDeviceID").val("");
    $(".info-box").removeClass("show");
    $(".info-box").css("display","none");
    // var deviceId = $("#btnCloseList").attr("data-id");
    $("#floor-list").find("a").removeClass("cur");
    $("#deviceInfo").html("");
    $(".t-building").css("height","100%");
    setTimeout(function() {
        autoWidth();
    }, 250);
});

//可视化组件
$(window).resize(function(){
    autoWidth();
});
function autoWidth(){
    var w=$(".floor-image.cur img")[0].offsetWidth;
    $(".floor-image.cur").css("width",w+"px");
}

//开门
//获取本地IP地址
$(document).on("click","#btnConDoor",function(){
    var deviceAds=$("#deviceInfo .titleLocation").html();
    //显示提示内容
    $("#modalSwitch .content").html("是否打开?<br/>"+deviceAds);
    $("#modalSwitch").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
});


//开门确认
//确认执行开关
$("#btnConfirm").on("click",function(){
    $("#modalSwitch").modal("hide");
    var ip = $(".menjin.cur").attr("data-ip");
    var interfaceaddr = $(".menjin.cur").attr("data-interfaceaddr");
    var dCode =$("#deviceInfo .d-code").html();
    var lastW = dCode.substring(dCode.length-1,dCode.length).toUpperCase();

    var functioncodeD = 0;
    if(lastW == "R"){
        functioncodeD = 16;
    }

    if(ip!="" && interfaceaddr!=""){
        if(lastW != "L" && lastW != "R"){
            //开左门
            getControlAccess(ip,interfaceaddr,0);
            //开右门
            getControlAccess(ip,interfaceaddr,16);
        }
        else{
            getControlAccess(ip,interfaceaddr,functioncodeD);
        }

    }

});

function getControlAccess(ip,interfaceaddr,functioncodeD){
    $.ajax({
        timeout : 20000,
        type:"get",
        url: ipg_url+"/ipg/door/openDoor",
        async:true,
        dataType: "text",
        data:{
            id:ip,
            target:interfaceaddr,
            functioncode:functioncodeD,
            state:'2'
        },
        success:function (result) {
            if(result=="success"){
                tipModal("icon-checkmark", "门禁设备打开中");
            }
            else{
                tipModal("icon-cross", "门禁设备打开失败");
            }
        },
        error:function (result) {
            tipModal("icon-cross", "门禁设备打开失败");
        }
    });
}

//一键开启所有门
// $("#btnOpenAll").click(function(){
//     $("#modalSwitchAll").modal({
//         keyboard: true,
//         backdrop: 'static'
//     }).on('show.bs.modal', centerModal());
//     $(window).on('resize', centerModal());
// });

//点击确认开启所有门禁设备
// $("#btnConfirmAll").click(function(){
//     $("#modalSwitchAll").modal("hide");
//     //填写开启所有门的接口
//     PostForm("/cwp/front/sh/ipg!execute", "uid=ipg006", "", opendoor, '',"");
// });

// function opendoor(result){
//     if(result.returnCode=="0"){
//         tipModal("icon-checkmark", "开门成功");
//     }
//     else{
//         tipModal("icon-cross", "开门失败");
//     }
// }